//
//  XMPPSharedInstance.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/11/27.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "XMPPSharedInstance.h"
#import "WinkAlertView.h"
#import "TelephonyInfo.h"
#import "FiendFriend.h"
#import "AppDelegate.h"
#import "MFSideMenu.h"
#import "NetworkManager.h"
#import "UserInfoModel.h"
#import "MessageStatus.h"

//XCLIENT {
#include "libxclient.h"
#include "lame.h"
//XCLIENT }



XMPPSharedInstance *XMPP;
#define XMPP_SERVER_ID "xmpp.mooredoll.com"

@implementation XMPPSharedInstance
@synthesize state=_state;
- (id)init{
    self = [super init];
    //如果生出自己就 呼叫loadDB
    if (self) {
        
        //增加KVO 去監聽 state
        [self addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
        
    }
    //把自己回傳出去
    return self;
}

+(XMPPSharedInstance *)sharedInstance{
    if (XMPP==nil) {
        XMPP = [[XMPPSharedInstance alloc]init];
    }
    return XMPP;
}

//狀態改變的時候
-(void)setState:(int)state
{
    //    [self willChangeValueForKey:@"state"];
    _state = state;
//    [self didChangeValueForKey:@"state"];
}

//連線狀態的 kvo delegate
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    if ([keyPath isEqualToString:@"state"]) {
        
        //登入中  0 & 1
        if ([change[@"old"]intValue] == STATE_XMPP_DISCONNECTED && [change[@"new"]intValue] == STATE_XMPP_CONNECTING) {
            NSLog(@"登入中");
            
            //登入成功  1 & 2
        }else if ([change[@"old"]intValue] == STATE_XMPP_CONNECTING && [change[@"new"]intValue] == STATE_XMPP_CONNECTED) {
            NSLog(@"登入成功");
            
            //結束等待畫面
            [XMPP.AV_Loading dismissWithClickedButtonIndex:0 animated:YES];
            //登入成過 儲存已登入過
            [[NSUserDefaults standardUserDefaults]setBool:1 forKey:@"login"];
            //這裏儲存 會儲存 帳號 密碼 國碼
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            //回饋訊息
            if (XMPP.stateDelegate && [XMPP.stateDelegate respondsToSelector:@selector(connectState:)]) {
                [XMPP.stateDelegate connectState:XMPP.state];
            }
            
            //登入中 登入失敗 1 & 4
        }else if ([change[@"old"]intValue] == STATE_XMPP_CONNECTING && [change[@"new"]intValue] == STATE_XMPP_POSSWORD_ERROR)
        {
            NSLog(@"登入失敗 或者是 帳號密碼錯誤");
            
            [XMPP.AV_Loading setTitle:@"登入失敗"];
            [XMPP.AV_Loading setMessage:@"密碼錯誤"];
            
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"password"];
            
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"account"];
            //改為未登入過
            [[NSUserDefaults standardUserDefaults]setBool:0 forKey:@"login"];
            
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            //2秒後關alert view
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [XMPP.AV_Loading dismissWithClickedButtonIndex:0 animated:NO];
            });
            NSLog(@"%i",XMPP.state);
            
            [XMPP.AV_Loading setTitle:@"登入中"];
            [XMPP.AV_Loading setMessage:@"請等待..."];
            
            //回饋訊息
            if (XMPP.stateDelegate && [XMPP.stateDelegate respondsToSelector:@selector(connectState:)]) {
                [XMPP.stateDelegate connectState:XMPP.state];
            }
            
            //改回成STATE_XMPP_DISCONNECTED 表示未登入
            XMPP.state = STATE_XMPP_DISCONNECTED;
            
            //連接不上網路 但是有登入過 1 & 0
        }else if([change[@"old"]intValue] == STATE_XMPP_CONNECTING && [change[@"new"]intValue] == STATE_XMPP_DISCONNECTED && [[NSUserDefaults standardUserDefaults]objectForKey:@"login"])
        {
            
            [XMPP.AV_Loading setTitle:@"登入失敗"];
            [XMPP.AV_Loading setMessage:@"網路未連結"];
            
            //2秒後關alert view
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [XMPP.AV_Loading dismissWithClickedButtonIndex:0 animated:NO];
                [XMPP.AV_Loading setTitle:@"登入中"];
                [XMPP.AV_Loading setMessage:@"請等待..."];
                
            });
            NSLog(@"%i",XMPP.state);
            
            //回饋訊息
            if (XMPP.stateDelegate && [XMPP.stateDelegate respondsToSelector:@selector(connectState:)]) {
                [XMPP.stateDelegate connectState:XMPP.state];
            }
            
        }
        //斷線 2 & 0
        else if ([change[@"old"]intValue] == STATE_XMPP_CONNECTED && [change[@"new"]intValue] == STATE_XMPP_DISCONNECTED){
            NSLog(@"斷線");
            
            //這邊監控網路狀態
            [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
                switch (status) {
                    case AFNetworkReachabilityStatusReachableViaWiFi:
                        
                        if (![[TelephonyInfo currentWifiName]hasPrefix:@"MDAP"]) {
                            
                            NSLog(@"回到網路狀態");
                            //重新連線
                            double delayInSeconds = 2.0;
                            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                                if (delayInSeconds != 0.0) {
                                    [XMPP login];
                                }
                            });
                        }
                        break;
                    case AFNetworkReachabilityStatusNotReachable:
                        NSLog(@"無效網路");
                    default:
                        break;
                }
            }];
            
            
            
            
            //登出 3
        }else if ([change[@"new"]intValue] == STATE_XMPP_LOGOUT)
        {
            
            if (XMPP.stateDelegate && [XMPP.stateDelegate respondsToSelector:@selector(connectState:)]) {
                [XMPP.stateDelegate connectState:XMPP.state];
            }
            
            NSLog(@"登出");
            
            //密碼錯誤 4
        }else if ([change[@"new"]intValue] == STATE_XMPP_POSSWORD_ERROR)
        {
            NSLog(@"密碼錯誤");
            
            
            //連接不上網路 但是沒有登入過 1 & 0
        }else if ([change[@"old"]intValue] == STATE_XMPP_CONNECTING && [change[@"new"]intValue] == STATE_XMPP_DISCONNECTED && ![[NSUserDefaults standardUserDefaults]objectForKey:@"login"])
        {
            NSLog(@"註冊時登入就失敗");
            [self.AV_Loading dismissWithClickedButtonIndex:0 animated:YES];
        }
    }
}

-(void)loginXMPP
{
    //提出帳號密碼
    NSString *account = [[NSUserDefaults standardUserDefaults]objectForKey:@"account"];
    NSString *password = [[NSUserDefaults standardUserDefaults]objectForKey:@"password"];
    
    //如果帳號 和密碼 都存在
    if (account != nil && password != nil) {
        
        if (self.AV_Loading == nil) {
            self.AV_Loading = [[UIAlertView alloc]initWithTitle:@"登入中" message:@"請等待..." delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
        }
        [self.AV_Loading show];
        
        //登入
        [self login];
    }
    
}
- (void)logoutXMPP
{
    self.state = STATE_XMPP_LOGOUT;
    //改為未登入過
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"password"];
    
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"account"];
    //改為未登入過
    [[NSUserDefaults standardUserDefaults]setBool:0 forKey:@"login"];
    
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    xclient_fin();
}


-(void)login
{
    //製作一個標籤
    xmppQueueTag = &xmppQueueTag;
    
    //建立一個執行緒
    xmppQueue = dispatch_queue_create("xmpp", NULL);
    
    
    /*
     什麼是可重入，來自維基百科：若一個程序或子程序可以「安全的被併行執行(Parallel computing)」，則稱其為可重入（reentrant或re-entrant）的。
     即當該子程序正在運行時，可以再次進入並執行它（並行執行時，個別的執行結果，都符合設計時的預期）。
     https://developer.apple.com/library/mac/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html#//apple_ref/c/func/dispatch_queue_set_specific
     */
    //放入可以重入的線程  帶入執行緒 標籤 環境上下文
    dispatch_queue_set_specific(xmppQueue, xmppQueueTag, xmppQueueTag, NULL);
    
    NSError *error = nil;
    
    //執行
    [self xclientEventTask:&error];
    
    
}

//改變Vcard
- (void)changeVCard:(NSDictionary *)userInfo
{
    NSString *name = [userInfo[@"userName"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *imagePath = userInfo[@"userImage"];
    
    NSLog(@"%@",name);
    NSLog(@"%@",imagePath);
    
    if (self.AV_GetUserInfoLoading == nil) {
        self.AV_GetUserInfoLoading = [[UIAlertView alloc]initWithTitle:@"傳送中" message:@"請等待..." delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    }
    [self.AV_GetUserInfoLoading show];
    
    //改變Vcard 不會有回傳值
    xclient_vcard_set_withpath("", (char*) [name UTF8String], (char*) [imagePath UTF8String]);//USER
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        //發送的同時在去取得 vcard
        [self getVCard];
    });
    //重新取得Vcard
    
}

-(void)getVCard
{
    
    NSString *userJID = [[NSUserDefaults standardUserDefaults]valueForKey:@"userJID"];
    
    //取得Vcard 帶入使用者 jid
    xclient_vcard_get((char*) [userJID UTF8String]);//USER or TOY
    
}

-(void)changeToyVcard:(NSDictionary *)toyInfo
{
    NSLog(@"%@",toyInfo);
    //將娃娃的jid 分離
    NSArray *array = [toyInfo[@"toyJid"] componentsSeparatedByString:@"@"];
    NSLog(@"%@",array);
    //取得jid 並添加"@bbserver-virtualbox"
    NSString *toyJid = [array[0] stringByAppendingString:@"@bbserver-virtualbox"];
    NSLog(@"%@",toyJid);

    //將名稱 轉utf 8
    NSString *name = [toyInfo[@"toyNickName"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    //圖片路徑
    NSString *imagePath = toyInfo[@"toyImage"];
    
    NSLog(@"%@",imagePath);

    
    //檢查有沒有路徑
    if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
        
        if (self.AV_SetToyVcardLoading == nil) {
            self.AV_SetToyVcardLoading = [[UIAlertView alloc]initWithTitle:@"傳送圖片中" message:@"請等待" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
        }
        [self.AV_SetToyVcardLoading show];
        
        //發送 資料
        // array[0] = toyJid 不含@bbserver-virtualbox
        xclient_vcard_set_withpath((char*) [array[0] UTF8String], (char*) [name UTF8String], (char*) [imagePath UTF8String]);//TOY
    }
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        //發送的同時在去取得 vcard
        xclient_vcard_get((char*) [toyJid UTF8String]);//USER or TOY
    });
}


//取得朋友的Vcard 一次只能取得一次
-(void)getFriendVCard:(NSString *)JID
{
    
    JID = [JID stringByAppendingString:@"@bbserver-virtualbox"];
    xclient_vcard_get((char*) [JID UTF8String]);//USER or TOY
}

//取得朋友列表
-(void)getFriendRoster
{
    xclient_iq_get_roster_send();
}




//XCLIENT {
#define return_from_block  return
NSString *const XMPPStreamErrorDomain = @"XMPPStreamErrorDomain";
NSString *const XMPPStreamDidChangeMyJIDNotification = @"XMPPStreamDidChangeMyJID";
enum XMPPStreamState
{
    STATE_XMPP_DISCONNECTED, //0
    STATE_XMPP_CONNECTING, //1
    STATE_XMPP_CONNECTED, //2
    STATE_XMPP_LOGOUT, //3
    STATE_XMPP_POSSWORD_ERROR, //4
    
};
enum XMPPStreamErrorCode
{
    XMPPStreamInvalidState,      // Invalid state for requested action, such as connect when already connected 無效狀態，請求的動作，例如連接已經連接時
};
char *_str_text(char *text)
{
    static char str[512];
    if(text == 0)return "";
    NSInteger len = strlen(text);
    if(len > 512){
        sprintf(str, "%.8s~~~~%ld~~~~%.8s", text, (long)len, &text[len - 8]);
        text = str;
    }
    return(text);
}



- (BOOL)xclientEventTask:(NSError **)errPtr
{
    my_cb_event_register(&my_event_func);
    
    __block BOOL result = NO;
    __block NSError *err = nil;
    
    //創建一個 block 自動釋放池存儲於內存中的棧中遵循"先進後出"原則
    dispatch_block_t block =
    ^{ @autoreleasepool {
        //#pragma mark  Tank 如果狀態 是已經連線或著連線中
        if (_state != STATE_XMPP_DISCONNECTED)
        {
            
            #warning Tank 多語系這部分要更改
            NSString *errMsg = @"Attempting to connect while already connected or connecting.";
            
            NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
            
            err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
            if (err)
            {
                
                NSLog(@"error %@",[[err userInfo]objectForKey:NSLocalizedDescriptionKey]);
            }
            
            result = NO;
            return_from_block;
        }
        
        //state = STATE_XMPP_CONNECTING;//set from xclient_event
        
        
        //#pragma mark  Tank 登入後 會產生 兩個資料夾到手機端 receive(收到) ＆ record(錄音)
        [self init_file_folder];
        
        //xclient_init("23.99.108.70", "jerry@bbserver-virtualbox", "qwer1234");
        NSString *receiveDir = [NSHomeDirectory() stringByAppendingString:@"/Documents/receive/"];
        NSLog(@"%@",receiveDir);
        
        
        //#pragma mark  Tank 測試網址 帳號 密碼 輸入的地方
        
        //取出加了國碼的帳號
        NSString *account = [TelephonyInfo accountAddCountryCode];
        
        //再加上server
        account = [account stringByAppendingString:@"@bbserver-virtualbox"];
        
        NSLog(@"account = %@",account);
        NSString *password = [[NSUserDefaults standardUserDefaults]objectForKey:@"password"];
        NSLog(@"password = %@",password);
        

        xclient_init("xmpp.mooredoll.com", (char*) [account UTF8String], (char*) [password UTF8String], (char*)[receiveDir UTF8String]);
    }};
    
    //檢查目前是否正在執行 xmppQueueTag 這個執行緒 如果沒有 則執行         dispatch_sync(xmppQueue, block);
    
    if (dispatch_get_specific(xmppQueueTag))
        block();
    else
        //同步執行
        dispatch_sync(xmppQueue, block);
    
    return result;
}
#pragma mark 創建資料路徑
- (void)init_file_folder
{
    NSFileManager *fm = [NSFileManager new];
    NSString *receiveDir = [NSHomeDirectory() stringByAppendingString:@"/Documents/receive"];
    if (![fm createDirectoryAtPath:receiveDir withIntermediateDirectories:YES attributes:nil error:nil]) {
        //TODO:show something
    }
    NSString *recordDir = [NSHomeDirectory() stringByAppendingString:@"/Documents/record"];
    if (![fm createDirectoryAtPath:recordDir withIntermediateDirectories:YES attributes:nil error:nil]) {
        //TODO:show something
    }
}


#pragma mark  Tank 這是回傳的方法 登入的回傳
void my_event_func(char *a[], int n) // this is call back method
{
    
    
    NSString *events_type = nil;
    NSMutableArray *events_row = [NSMutableArray array];
    
    for(int i = 0; i < n; i++)
    {
        char *s = a[i];
        if(s == 0)s = "<null>";
        s = _str_text(s);
        if((i & 0x01) == 0x01)
        {
            //NSLog(@"(%s)", s);
        }
        else
        {
            //NSLog(@" %s", s);
        }
        [events_row addObject:[NSString stringWithFormat:@"%s", s]];
    }
    
    if ([events_row count]==0)
        return;
    
    events_type = events_row[0];
    
    
    NSMutableDictionary *results;
    if (results)
        [results removeAllObjects];
    else
        results = [@{}mutableCopy];
    
    NSLog(@"------------------------");
    for (int i=0; i < n; i+=2)
    {
        [results setObject:events_row[i+1] forKey:events_row[i]];
        NSLog(@"key %@   :  值 %@",events_row[i],events_row[i+1]);
    }
    NSLog(@"------------------------\n");
    
    
    if ([events_type isEqualToString:@"state"])
    {//XMPP STATE
        //Tank 檢查狀態 如果有狀態是 state 則檢查連線情況
    
        dispatch_async(dispatch_get_main_queue(),
        ^{
            if ([events_row[1] isEqualToString:@"connecting"])
            {
                XMPP.state = STATE_XMPP_CONNECTING;//登入中
            }
            else if ([events_row[1] isEqualToString:@"connected"])
            {
                //登入成功 改變state的值
                XMPP.state = STATE_XMPP_CONNECTED;
                //連線中斷
            }
            else if ([events_row[1] isEqualToString:@"disconnected"])
            {
                //如果是 Cannot authenticate without resource 則表示帳號或密碼錯誤
                if (events_row.count >4 )
                {
                    
                    if ([events_row[5]isEqualToString:@"Cannot authenticate without resource"])
                    {
                        //密碼錯誤
                        XMPP.state = STATE_XMPP_POSSWORD_ERROR;
                    }
                    
                }
                else
                {
                    //斷線
                    XMPP.state = STATE_XMPP_DISCONNECTED;
                    
                }
            }
            else if ([events_row[1] isEqualToString:@"finish"])//傳送照片玩 網路會斷開
            {
                //NSLog(@"events_row = %@",events_row);
                //連線完畢
            }else
            {
                //NSLog(@"events_row = %@",events_row);
                
            }
            
        });
        
    }
    else if ([events_type isEqualToString:@"jid"])
    {
        //Tank 檢查狀態 如果有狀態是 jid 表示使用者的登入id
        // save jid to local
        NSString *string = [NSString stringWithFormat:@"%@",events_row[1]];
        NSArray *array = [string componentsSeparatedByString:@"@"];
        NSString *userJID = array[0];
        userJID = [userJID stringByAppendingString:@"@bbserver-virtualbox"];
        
        [UserDefaults set:userJID withKey:@"userJID"];
        
        [[UserInfoModel sharedInstance]setJID:userJID];
        
        [XMPP getVCard];
    }
    else if ([events_type isEqualToString:@"roster"])
    {
        //Tank 檢查狀態 如果有狀態是 roster 表示使用者的朋友名冊
        //Tank 將名冊字串分離成陣列
        //NSLog(@"---roster---");
        NSArray *rosterSplit = [events_row[1] componentsSeparatedByString:@","];
        
        //新增Array存放名冊所有人的jid
        NSMutableArray *tempRoster = [[NSMutableArray alloc] init];
        
        NSString *userJID = [[NSUserDefaults standardUserDefaults]valueForKey:@"userJID"];
        
        for (NSString *roster in rosterSplit)
        {
            //Tank 將名冊陣列做個檢查 只要 名冊內容的前綴 不是ftp@ 開頭 就取得名稱
            if (![roster hasPrefix:@"ftp@"])
            {
                //如果名冊jid跟user的jid相同，就不增加
                if (![roster isEqualToString:userJID])
                {
                    [tempRoster addObject:roster];
                }
            }
        }
        //Tank{
        //過濾了自己 與 ftp 剩餘的朋友列表
        [DBManage setFriend:tempRoster];
        //}
        
        
    }
    else if ([events_type isEqualToString:@"presence_on"])
    {

     //Tank 檢查狀態 如果有狀態是 presence_on 表示使用者 or 玩具 是上線狀態 內容的前綴 不是ftp@ 開頭 就取得名稱
        if (![events_row[1] hasPrefix:@"ftp@"])
        {
            
            // 有人上下線的時候 去改變 上下線狀態
            [DBManage changePresenceOnAndOffWithPresence:YES whoseJid:events_row[1]];
        }


    }
    else if ([events_type isEqualToString:@"presence_off"])
    {//USER/TOY offline
     //Tank 檢查狀態 如果有狀態是 presence_on 表示使用者的玩具 是下線狀態 內容的前綴 不是ftp@ 開頭 就取得名稱
        NSLog(@"---presence_off---");
        if (![events_row[1] hasPrefix:@"ftp@"])
        {
            
            [DBManage changePresenceOnAndOffWithPresence:YES whoseJid:events_row[1]];

        }
    
    }
    else if ([events_type isEqualToString:@"message_recv"])
    {
        //receive message from USER/TOY/SERVER
        //Tank 檢查狀態 如果有狀態是 message_recv 從使用者or娃娃orServer取得訊息
        if ([results[@"message_recv"] hasPrefix:@"messagestatus"])
        {
            dispatch_async(dispatch_get_main_queue(),
                           ^{
                               [[MessageStatus sharedInstance] getMessageRecv:results];
                           });
        }
        else
        {
            [[NetworkManager sharedInstance] reciveMessageFromServerWithDictionary:results];
        }
        
        
    }
    else if ([events_type isEqualToString:@"message_send"])
    {
        //Tank 檢查狀態 如果有狀態是 ftp_recv 開始接收檔案 內容包含 檔案路徑 從哪一位使用者的jid 誰與uid
        if ([results[@"message_send"] hasPrefix:@"OTASTATUS"])
        {
            
        }
        else
        {
            [[NetworkManager sharedInstance] sendDataSuccessWithDictionary:results];
        }
        
    }
    else if ([events_type isEqualToString:@"ftp_recv"])
    {
        //started receiving file
        //NSLog(@"---ftp_recv---");
        //NSLog(@"file(%@)", events_row[1]);//file path
        
        //NSLog(@"from(%@)", events_row[3]);//from jid
        
        //NSArray *sidSplit = [events_row[5] componentsSeparatedByString:@"_"];
        //NSLog(@"who(%@) uid(%@)", sidSplit[1], sidSplit[2]);//from who & uid
        [[NetworkManager sharedInstance] reciveDataFromFtpWithDictionary:results];
        
    }
    else if ([events_type isEqualToString:@"ftp_recv_progress"])
    {
        //Tank 檢查狀態 如果有狀態是 ftp_recv_progress 開始接收檔案 進度
       // NSLog(@"---ftp_recv_progress---");
       // NSLog(@"percentage(%@)", events_row[1]);//percentage 百分比
        
        //NSArray *sizeSplit = [events_row[3] componentsSeparatedByString:@"/"];
        //NSLog(@"received(%@) total(%@)", sizeSplit[0], sizeSplit[1]);//received/total 幾%
        
        //NSArray *sidSplit = [events_row[5] componentsSeparatedByString:@"_"];
        //NSLog(@"who(%@) uid(%@)", sidSplit[1], sidSplit[2]);//from who & uid 重哪裡
        [[NetworkManager sharedInstance] receiveFileProgressWithDictionary:results];

    }
    else if ([events_type isEqualToString:@"ftp_recv_end"])
    {
        //Tank 檢查狀態 如果有狀態是 ftp_recv_end 檔案接收完畢
       // NSLog(@"---ftp_recv_end---");
       // NSArray *sizeSplit = [events_row[1] componentsSeparatedByString:@"/"];
       // NSLog(@"received(%@) total(%@)", sizeSplit[0], sizeSplit[1]);//received/total
        
        //NSArray *sidSplit = [events_row[5] componentsSeparatedByString:@"_"];
       // NSLog(@"who(%@) uid(%@)", sidSplit[1], sidSplit[2]);//from who & uid
        
       // NSLog(@"file(%@)", events_row[7]);//file path
        
//        [[NetworkManager sharedInstance] reciveDataFromFtpWithDictionary:results];
        
    }
    else if ([events_type isEqualToString:@"link_recv_end"])
    {
        //NSLog(@"---link_recv_end---");
        //NSArray *sizeSplit = [events_row[1] componentsSeparatedByString:@"/"];
        //NSLog(@"received(%@) total(%@)", sizeSplit[0], sizeSplit[1]);//received/total
        
        //NSLog(@"from(%@)", events_row[3]);//received/total
        
//        NSArray *parametersSplit = [events_row[5] componentsSeparatedByString:@" "];
//        for (NSString *param in parametersSplit)
//        {
//            NSArray *paramSplit = [param componentsSeparatedByString:@"="];
//            NSLog(@"parameter(%@) value(%@)", paramSplit[0], paramSplit[1]);
//        }
//        NSLog(@"file(%@)", events_row[7]);//file path

    }
    else if ([events_type isEqualToString:@"ftp_send"])
    {
        //Tank 檢查狀態 如果有狀態是 ftp_send 檔案發送
//        NSLog(@"---ftp_send---");
//        NSLog(@"file(%@)", events_row[1]);//file path
//        
//        NSLog(@"to(%@)", events_row[3]);//to jid
//        
//        NSArray *sidSplit = [events_row[5] componentsSeparatedByString:@"_"];
//        NSLog(@"who(%@) uid(%@)", sidSplit[1], sidSplit[2]);//to who & uid
        [[NetworkManager sharedInstance] sendDataSuccessWithDictionary:results];

    }
    else if ([events_type isEqualToString:@"ftp_send_progress"])
    {
        [[NetworkManager sharedInstance] sendFileProgressWithDictionary:results];
    }
    else if ([events_type isEqualToString:@"ftp_send_end"])
    {
        //Tank 檢查狀態 如果有狀態是 ftp_send 檔案發送結束
//        NSLog(@"---ftp_send_end---");
//        NSArray *sizeSplit = [events_row[1] componentsSeparatedByString:@"/"];
//        NSLog(@"received(%@) total(%@)", sizeSplit[0], sizeSplit[1]);//sent/total
//        
        NSArray *sidSplit = [events_row[5] componentsSeparatedByString:@"_"];
//        NSLog(@"who(%@) uid(%@)", sidSplit[1], sidSplit[2]);//to who & uid
//        
//        NSLog(@"file(%@)", events_row[7]);//file path
        
        
        //[[NetworkManager sharedInstance] sendDataSuccessWithDictionary:results];
        //Tank 發送結束 如果是雙方？ 通知對方警告？
        //FUNCTION SET ALARM {
        if([sidSplit[0] isEqualToString:@"sida"])
        {
            ////!!!! ui_event !!!!tv=[Ljava.lang.String;@41ea03b0, type=ftp_send_end, value=14112/14112, value2=daughter@bbserver-virtualbox/1625aec6, value3=sida_mother_1406780913
            xclient_message_send("jerry2@bbserver-virtualbox", getAlarmString(true));
            //TODO:update dialog status & disable this dialog when receive the same message(getAlarmString) from MD
            return;
        }
        //FUNCTION SET ALARM }
    }
    else if ([events_type isEqualToString:@"ping_recv"])
    {
        //NSLog(@"%@",events_row);
    }
    else if ([events_type isEqualToString:@"vcard_get"])
    {
        //收到狀態
        
        dispatch_async(dispatch_get_main_queue(),
        ^{
            //NSLog(@"%@",results);
                        
            //檢查JID 是不是自己
            NSString *userJID = [UserDefaults get:@"userJID"];
            
            //如果jid 是自己
            if ([userJID hasPrefix:events_row[1]])
            {

                
                //記錄使用者自己的圖片位置
                NSString *userImagePath = [results objectForKey:@"PHOTO_PATH"] ? [results objectForKey:@"PHOTO_PATH"] : @"";
                
                UserInfoModel *userInfo = [[UserInfoModel sharedInstance]setDataWithName:results[@"NICKNAME"] andImagePath:userImagePath andPhoneNumber:nil andJID:results[@"vcard_get"]];
                
                
                //當使用者在上傳自己圖片的時候會近到下面這一個判斷 因為在使用者上傳圖片才會產生出 AV_GetUserInfoLoading
                if (XMPP.AV_GetUserInfoLoading!=nil)
                {
                    
                    [XMPP.AV_GetUserInfoLoading dismissWithClickedButtonIndex:0 animated:YES];
                    XMPP.AV_GetUserInfoLoading = nil;
                    
                    //執行delegate 通知已完成
                    if (XMPP.stateDelegate && [XMPP.stateDelegate respondsToSelector:@selector(getUserImageIsOK:)]){
                        [XMPP.stateDelegate getUserImageIsOK:results];
                    }

                }
                
                //觸發通知 看使有接收這個通知就可以得到使用者vcard 資料
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserInfo" object:userInfo];
                
            }
            else
            {
                //同步 roster
                [DBManage getVcardResult:results];

            }
            
                
            //取得vcard 使用 delegate 回傳回去  通訊錄搜尋好友使用的
            if (XMPP.getFriendVcardDelegate && [XMPP.getFriendVcardDelegate respondsToSelector:@selector(getFriendVcardResult:)])
            {
                [XMPP.getFriendVcardDelegate getFriendVcardResult:results];
            }
            
            
            //當AV_SetToyVcardLoading 就是代表在取得娃娃ＶＣＡＲＤ
            if (XMPP.AV_SetToyVcardLoading)
            {
                [XMPP.AV_SetToyVcardLoading dismissWithClickedButtonIndex:0 animated:NO];
                XMPP.AV_SetToyVcardLoading = nil;
                
                //如果是在 註冊完娃娃後 並且設定娃娃Vcard 時 這個delegate 會觸發
                if (XMPP.toyVcardDelegate && [XMPP.toyVcardDelegate respondsToSelector:@selector(setToyVcard)]) {
                    [XMPP.toyVcardDelegate setToyVcard];
                }
            }
        });
    }
}


//FUNCTION: ALARM SETUP {
int mbWeekDay1=1, mbWeekDay2=0, mbWeekDay3=1, mbWeekDay4=0, mbWeekDay5=0, mbWeekDay6=0, mbWeekDay7=0;//0 or 1
char *mSource = "0";//0:buildin; 1:voice; 2:mp3file
char *mSourcePath = "";
char *mAlarmOnOff = "0";//"0":"off", "1":"on"
char *mStopMethod = "1";//0:once; 1:touch; 2:lr; 3:ud; 4:tb; 5:shake
char *getAlarmString(int isremote)
{
    static char str[256] = {0};
    
    char *hour = "08";
    char *minute = "10";
    
    //example:if week1&week3 alarm-->days should be 1+4=5
    int days = 0;
    if(mbWeekDay1) days+=1;
    if(mbWeekDay2) days+=2;
    if(mbWeekDay3) days+=4;
    if(mbWeekDay4) days+=8;
    if(mbWeekDay5) days+=16;
    if(mbWeekDay6) days+=32;
    if(mbWeekDay7) days+=64;
    if(isremote) {
        //return "*remote-setalarm#" + (mAlarmOnOff.equals("1")?"on":"off") + "#" + mStopMethod +"#"+days+"#"+Integer.valueOf(txtHour.getText().toString())+"#"+Integer.valueOf(txtMinute.getText().toString())+"#"+mSource+"#"+(today.year%100)+"#"+(today.month+1)+"#"+today.monthDay+"#"+today.weekDay+"#"+today.hour+"#"+today.minute+"#"+today.second;//TEST (6)00:20, yy#mm#dd#hh#mm#ss
        memset(str, 0, sizeof(str));
        sprintf(str, "*remote-setalarm#%s#%s#%d#%s#%s#%s#0#0#0#0#0#0#0", strcmp(mAlarmOnOff, "0")==0?"off":"on", mStopMethod, days, hour, minute, mSource);
        return str;
    } else {
        return "";
    }
}
void set_alarm()
{
    
    
    if(strcmp(mSource,"1")==0 && strcmp(mSourcePath,"")==0) {
        //error ui setup
        return;
    }
    if(strcmp(mAlarmOnOff,"0")==0 || strcmp(mSource, "0")==0) {//Set as MD's build in alarm
        xclient_message_send("jerry2@bbserver-virtualbox", getAlarmString(true));
        //TODO:show dialog & disable this dialog when receive same message(getAlarmString) from MD 顯示對話框和關閉此對話框時，收到來自MD相同的消息（警告消息）
    } else {//Set as User's phone's mp3 clip
        //Ex:mSourcePath = "/sdcard/testalarm.mp3"
        //String[] a = mSourcePath.split("/");
        //xclient_alarm_send(mSourcePath, a[a.length - 1], "jerry2@bbserver-virtualbox");
        //TODO:show dialog-->see ftp_send_end
    }
}
//FUNCTION: ALARM SETUP }


//-(void)checkToyIsNewWithToyJid:(NSString *) toyJID andDBRoster:(NSArray *)array_myRoster;
//{
//    
//    //取出 朋友列表 檢查有沒有這個 jid 如果沒有 則觸發這是新的娃娃delegate
//    if (XMPP.getNewToyDelegate && [XMPP.getNewToyDelegate respondsToSelector:@selector(getNewToyResult:)]) {
//        
//        if (![toyJID hasPrefix:[[NSUserDefaults standardUserDefaults]objectForKey:@"userJID"]]) {
//            
//            
//            __block BOOL isInstall = YES;
//            
//            //逐一檢查 朋友列表 如果有 則 isInstall ＝ no
//            
//            [array_myRoster enumerateObjectsUsingBlock:^(FriendRoster* obj, NSUInteger idx, BOOL *stop) {
//                if ([toyJID hasPrefix:obj.jid]) {
//                    isInstall = NO;
//                }
//            }];
//            
//            //如果 isInstall ＝ yes 則觸發delegate
//            if (isInstall) {
//                //收到 娃娃的JID 以後 先去檢查ＤＢ看有沒有這一隻娃娃 沒有則是新的
//                //檢查還沒有寫好
//                NSLog(@"新娃娃");
//                [XMPP.getNewToyDelegate getNewToyResult:toyJID];
//                
//            }
//        }
//    }
//}




@end
